package com.bitsfromspace.ubertorrent.tracker;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Trackers contains a list of {@link TrackerTier}s.
 * <br/>
 * 
 * {@link #getNextTrackersToAnnounce()} Returns the next tracker to announce for all underlying {@link TrackerTier}.
	 * <br/>
	 * The next tracker is selected by calling {@link TrackerTier#getNextAnnounceTracker()}
	 * on all tiers and selecting the tracker with the lowest {@link Tracker#getNextAnnounceDate()}.
 * 
 * 
 * @author: chris.oudeman
 * @since: Jan 5, 2011
 */
public class Trackers {

	private final List<TrackerTier> tiers;

	public Trackers(List<TrackerTier> tiers) {

		this.tiers = tiers;
	}

	/**
	 * Returns the next tracker to announce for all underlying {@link TrackerTier}.
	 * <br/>
	 * The next tracker is selected by calling {@link TrackerTier#getNextAnnounceTracker()}
	 * on all tiers and selecting the tracker with the lowest {@link Tracker#getNextAnnounceDate()}.
	 */
	public Tracker getNextTrackersToAnnounce() {

		List<Tracker> trackers = new ArrayList<Tracker>();
		for (TrackerTier tier : tiers) {
			Tracker tracker = tier.getNextAnnounceTracker();
			if (tracker != null) {
				trackers.add(tracker);
			}
		}
		if (trackers.isEmpty()) {
			return null;
		}

		Collections.sort(trackers, TRACKERS_COMPARATOR);
		return trackers.get(0);

	}

	/**
	 * Returns a copy of all tiers.
	 */
	public List<TrackerTier> getTiers() {

		return new ArrayList<TrackerTier>(tiers);
	}

	public static final Comparator<Tracker> TRACKERS_COMPARATOR =
			new Comparator<Tracker>() {

				@Override
				public int compare(Tracker t1, Tracker t2) {

					long deltaAnnounce =
							t1.getNextAnnounceDate() - t2.getNextAnnounceDate();

					if (deltaAnnounce == 0) {
						//Random select one......
						if (Math.random() * 2 < 1.0) {
							return -1;
						} else {
							return 1;
						}
					}
					return (int) deltaAnnounce;

				}
			};

}


